<template>
  <layout>
    <template slot="title" v-if="!currentPublishId">
      <span style="margin-right: 40px;">农户耕地与种粮信息管理</span>
      <a-button-group>
        <a-button
          type="primary"
          icon="cloud-upload"
          @click="$refs.GrainImport.handlerUploadExecl()"
        >导入单机版补贴面积数据</a-button>
        <a-button
          type="default"
          icon="download"
          style="margin-right: 20px;"
          @click="handlerDownload($downloadGrainsUrl)"
        >
          下载模板
        </a-button>
      </a-button-group>

      <a-button
        type="dashed"
        icon="question-circle"
        @click="events.trigger('show-helper')"
      >
        帮助
      </a-button>
    </template>

    <!-- 顶部操作 -->
    <section slot="search">
      <custom-form
        ref="search-form"
        class="search-form"
        v-model="tableSearch"
        layout="inline"
        mode="search"
        :FormList="searchColumns"
      >
        <a-button
          class="action-button"
          type="primary"
          @click="search()"
        >搜索</a-button>
      </custom-form>
      <!-- <a-input placeholder="产品名称或者编号" v-model="tableSearch.searchKey" allowClear style="width: 200px;" /> -->
    </section>

    <!-- 产品列表 -->
    <a-table
      class="grain-table table-total"
      :dataSource="tableData"
      :columns="tableColumns"
      :rowKey="record => record.usr_id"
      :pagination="false"
      :loading="tableLoading"
      :customRow="customTableRow"
      :scroll="{
        y: tableClientHeight,
        x: '100%'
      }"
      @change="handleTableChange"
      bordered
    >
      <template
        slot="pay_unit"
        slot-scope="row"
      >
        {{getLabel(row.pay_unit, [], 'pay_unit')}}
      </template>
      <template
        slot="field"
        slot-scope="row"
      >
        {{ row.field || 0}}
      </template>
      <template
        slot="bt_size"
        slot-scope="row, record, index"
      >
        <a-input v-if="row.bt_size_isEdit" ref="bt_size" v-model="row.bt_size" @blur="row.bt_size_isEdit = false" default placeholder="请输入补贴面积" >
           <a-tooltip slot="suffix" title="点击保存">
            <a-icon type="check-circle" :style="{ color: '#52c41a' }" @click="handerChangeBtSize(row)" />
          </a-tooltip>
        </a-input>
        <a-button
          type="link"
          showDefaultLabel
          v-else
          @click="handlerChangeEdit(row, index)"
        >{{row.bt_size || 0}}</a-button>
      </template>

      <template
        slot="field1"
        slot-scope="row, record, index"
      >
        <span v-if="index === 0">
          {{row.field1 || 0}}
        </span>
        <a-button
          v-else
          type="link"
          :auth="['member-grain.field-list', 'publish.member-list']"
          showDefaultLabel
          @click="handlerManageFarmLand(row, 1)"
        >{{row.field1 || 0}}</a-button>
      </template>
      <template
        slot="field2"
        slot-scope="row, record, index"
      >
        <span v-if="index === 0">
          {{row.field2 || 0}}
        </span>
        <a-button
          v-else
          type="link"
          :auth="['member-grain.field-list', 'publish.member-list']"
          showDefaultLabel
          @click="handlerManageFarmLand(row, 2)"
        >{{row.field2 || 0}}</a-button>
      </template>
      <template
        slot="field3"
        slot-scope="row, record, index"
      >
        <span v-if="index === 0">
          {{row.field3 || 0}}
        </span>
        <a-button
          v-else
          type="link"
          :auth="['member-grain.field-list', 'publish.member-list']"
          showDefaultLabel
          @click="handlerManageFarmLand(row, 3)"
        >{{row.field3 || 0}}</a-button>
      </template>
      <template
        slot="plant"
        slot-scope="row, record, index"
      >
        <span v-if="index === 0">
          {{(+row.plant || 0).toFixed(3)}}
        </span>
        <a-button
          v-else
          type="link"
          :auth="['member-grain.edit', 'publish.member-list']"
          showDefaultLabel
          @click="handleTableEdit(row, 'grain')"
        >{{(+row.plant || 0).toFixed(3)}}</a-button>
      </template>
      <!-- 按钮区 -->
      <template
        slot="action"
        slot-scope="row"
      >
        <a-button
          class="action-button"
          type="primary"
          size="small"
          @click="handleTableEdit(row, 'farmland')"
        >管理确权面积</a-button>
        <a-button
          class="action-button"
          type="primary"
          size="small"
          @click="handleTableEdit(row, 'grain')"
        >管理粮食面积</a-button>
        <!-- <a-popconfirm
          title="您确认要删除该条数据?"
          ok-text="确认"
          cancel-text="取消"
          @confirm="tableDel(row)"
        >
          <a-button
            class="action-button"
            type="danger"
            size="small"
          >删除</a-button>
        </a-popconfirm> -->
        <!-- <a-button
          class="action-button"
          type="primary"
          size="small"
          @click="handleTableEdit(row)"
        >项目管理</a-button> -->
      </template>
    </a-table>

    <!-- 产品列表分页器 -->
    <a-pagination
      slot="paging"
      :pageSizeOptions="pageSizes"
      :total="total"
      :show-total="showTotal"
      showSizeChanger
      :pageSize="pageSize"
      v-model="currentPage"
      @showSizeChange="changePageSize"
      @change="changePage"
    >
    </a-pagination>

    <!-- 编辑产品数据 -->
    <a-modal
      :visible="visible"
      :title="visibleTitle"
      centered
      v-bind="Boolean(currentPublishId) ? {footer: null} : {}"
      @cancel="visible = false"
      cancelText="关闭"
      okText="保存"
      @ok="handleSubmit"
    >
      <custom-form
        ref="custom-form"
        class="custom-form"
        v-model="currentRow"
        :FormList="formColumns"
        :mode="customMode"
        v-bind="formItemLayout"
        layout="horizontal"
      ></custom-form>
    </a-modal>

    <GrainImport ref="GrainImport" />

    <!-- 管理耕地信息 -->
    <a-modal
      :title="currentRow.member_nam + '-当前确权耕地汇总表'"
      placement="right"
      width="80%"
      :visible="drawerVisible"
      :footer="null"
      :bodyStyle="{ maxHeight: '80vh', minHeight: '60vh' }"
      @cancel="drawerVisible = false"
    >
      <Farmland
        :currentField="currentRow"
        :currentFieldType="currentFieldType"
        :isReadOnly="Boolean(currentPublishId)"
        :currentPublishId="currentPublishId"
      />
    </a-modal>

  </layout>
</template>

<script lang="ts">
import { Mixins, Component, Watch, Vue, Prop } from 'vue-property-decorator'
import { State, Mutation, Getter, namespace } from 'vuex-class'
import EventsMixin from '@/mixin/events'
import { TableMixin, AuthMixin, AppMixin } from '@/mixin'

import { TableLayout } from '@/layouts'
import CustomForm from '@/components/src/Form'
import { userServices, IAdmin } from '@/common/services'
import { famerServices, IMember, IGrain } from '@/common/services/famer'
import { publishServices } from '@/common/services/publish'
import { commonServices } from '@/common/services/common'
import { memberRole, PayUnitType } from '@/common/enum'
import Farmland from './Farmland.vue'
import GrainImport from './GrainImport.vue'

@Component({
  components: {
    Layout: TableLayout,
    CustomForm,
    Farmland,
    GrainImport
  }
})
export default class AdminList extends Mixins(
  EventsMixin,
  TableMixin,
  AuthMixin,
  AppMixin
) {
  @Prop({
    type: String
  })
  public currentAreaId!: string

  @Prop({
    type: String
  })
  public currentPublishId!: string

  public commonParams = {
    s_a_id: '',
    family_id: '',
    pub_id: this.currentPublishId
  }

  // 产品列表搜索条件
  public tableSearch = {
    member_nam: ''
  }

  // 自定义mode
  public customMode = ''

  // 产品列表表格信息
  public columns: ITable.IColumn[] = [
    {
      title: '农户编号',
      dataIndex: 'family_id',
      key: 'family_id',
      width: 170,
      form: {
        type: 'a-input',
        placeholder: '请输入农户编号',
        isShowQuery: true,
        isShowFrom: false
      }
    },
    {
      title: '户主姓名',
      dataIndex: 'member_nam',
      key: 'member_nam',
      width: 90,
      form: {
        type: 'a-input',
        placeholder: '请输入户主姓名',
        isShowQuery: true,
        isShowFrom: false
      }
    },
    {
      title: '家庭住址',
      dataIndex: 'member_addr',
      key: 'member_addr',
      width: 300
    },
    {
      title: '确权面积（亩）',
      children: [
        {
          title: '小计',
          scopedSlots: { customRender: 'field' },
          key: 'field',
          width: 110,
          align: 'right',
          form: {
            type: 'a-input',
            placeholder: '请输入耕地总面积',
            renderMode: ['farmland']
          }
        },
        {
          title: '承包地',
          scopedSlots: { customRender: 'field1' },
          key: 'field1',
          align: 'right',
          width: 110,
          sorter: true,
          sortDirections: ['ascend', 'descend'],
          form: {
            type: 'a-input',
            placeholder: '请输入承包地面积',
            renderMode: ['farmland'],
            isShowQuery: true,
            querySection: true
          }
        },
        // {
        //   title: '增加面积',
        //   scopedSlots: { customRender: 'field2' },
        //   key: 'field2',
        //   width: 100,
        //   sorter: true,
        //   sortDirections: ['ascend', 'descend'],
        //   form: {
        //     type: 'a-input',
        //     placeholder: '请输入增加面积',
        //     renderMode: ['farmland'],
        //     isShowQuery: true,
        //     querySection: true
        //   }
        // },
        {
          title: '增加面积',
          scopedSlots: { customRender: 'field2' },
          key: 'field2',
          width: 110,
          align: 'right',
          sorter: true,
          sortDirections: ['ascend', 'descend'],
          form: {
            type: 'a-input',
            placeholder: '请输入增加面积',
            renderMode: ['farmland'],
            isShowQuery: true,
            querySection: true
          }
        },
        {
          title: '减少面积',
          scopedSlots: { customRender: 'field3' },
          key: 'field3',
          width: 110,
          align: 'right',
          sorter: true,
          sortDirections: ['ascend', 'descend'],
          form: {
            type: 'a-input',
            placeholder: '请输入增加面积',
            renderMode: ['farmland'],
            isShowQuery: true,
            querySection: true
          }
        },
        // {
        //   title: '租出地',
        //   scopedSlots: { customRender: 'field3' },
        //   key: 'field3',
        //   width: 100,
        //   sorter: true,
        //   sortDirections: ['ascend', 'descend'],
        //   form: {
        //     type: 'a-input',
        //     placeholder: '请输入租出地',
        //     renderMode: ['farmland'],
        //     isShowQuery: true,
        //     querySection: true
        //   }
        // },
      ]
    },
    {
      title: '粮食种植面积（亩）',
      key: 'plant',
      align: 'right',
      sorter: true,
      sortDirections: ['ascend', 'descend'],
      width: 120,
      scopedSlots: { customRender: 'plant' },
      form: {
        type: 'a-input',
        placeholder: '粮食种植面积',
        isShowQuery: true,
        querySection: true,
        isShowFrom: false
      }
    },
    // {
    //   title: '补贴面积',
    //   key: 'bt_size',
    //   align: 'center',
    //   width: 120,
    //   scopedSlots: { customRender: 'bt_size' }
    // }
    // {
    //   title: '操作',
    //   key: 'action',
    //   width: 300,
    //   scopedSlots: { customRender: 'action' }
    // }
    {
      title: '备注',
      dataIndex: 'readme',
      key: 'readme',
      width: this.isLargeScreen ? 'auto' : 300
    },
  ]

  // 金额相关字段
  public moneyFields: ITable.IColumn[] = [
    {
      title: '补贴标准（亩/元）',
      dataIndex: 'pay_price',
      width: 100,
      align: 'center',
      key: 'pay_price'
    },
    {
      title: '补贴核算依据',
      scopedSlots: { customRender: 'pay_unit' },
      key: 'pay_unit',
      width: 120,
      form: {
        type: 'a-select',
        placeholder: '请选择补贴核算依据',
        isShowFrom: false,
        dict: PayUnitType
      }
    },
    {
      title: '补贴总金额（元）',
      dataIndex: 'pay_total',
      width: 110,
      align: 'center',
      key: 'pay_total'
    }
  ]

  public tableApi = {
    list: this.currentPublishId
      ? publishServices.getPublishUsers
      : famerServices.getMemberGrain,
    add: famerServices.updateMemberPlant,
    edit: famerServices.updateMemberPlant,
    // imageUpload: 'uploadStoreImage',
    // imageRemove: 'delStoreImage'
  }

  @Watch('currentAreaId')
  @Watch('currentPublishId', { immediate: true })
  public handlerCurrentAreaIdChange() {
    // 清空family_id 处理农户列表跳转过来的指定农户
    this.commonParams.family_id = ''
    // 公示页面进入
    if (this.currentPublishId) {
      this.commonParams.pub_id = this.currentPublishId
    } else {
      if (!this.currentAreaId) return
      this.commonParams.s_a_id = this.currentAreaId
    }
    this.getData()
  }

  public mounted() {
    // 公示下添加金额相关字段
    if (this.currentPublishId) {
      this.columns.push(...this.moneyFields)
    }
    this.handlerAddGrainColumn()

    // 农户列表跳转过来
    const id = this.$route.query.s_a_id as string
    if (id) {
      this.commonParams.family_id = this.$route.query.id as string
      this.commonParams.s_a_id = id
      this.getData()
    }
  }

  public handlerAddGrainColumn() {
    const grains = [
      '水稻',
      '玉米',
      '小麦',
      '红苕',
      '马铃薯',
      '大豆',
      '绿豆',
      '豌葫豆',
      '高粱',
      '荞麦',
      '肾豆',
      '红小豆'
    ]
    const grainsColumns = grains.map((item, index) => {
      const key = 'plant' + (index + 1)
      return {
        title: item,
        dataIndex: key,
        key,
        form: {
          type: 'a-input',
          placeholder: `请输入${item}面积`,
          renderMode: ['grain'],
          isShowList: false
        }
      }
    })
    this.columns = this.columns.concat(grainsColumns)
  }

  public async getData() {
    // @fix 修复直接刷新页面时没有s_a_id 接口异常问题
    if (!this.currentPublishId && !this.commonParams.s_a_id) return
    const res = await this.getTableList()
  }

  public handlerTableAdd() {
    this.tableAdd()
    this.$nextTick(() => {
      this.currentRow = Object.assign(
        {},
        { s_a_id: this.currentAreaId, role: 1 }
      )
    })
  }

  public handlerFamily(row: IMember) {
    this.events.trigger('select-houseHolder', row)
  }

  // 编辑前数据预处理
  public async handleTableEdit(row: IGrain, mode: string) {
    this.customMode = mode

    const methods = this.currentPublishId
      ? publishServices.getPublishUserPlants
      : famerServices.getMemberPlant
    methods({
      family_id: row.family_id,
      s_a_id: row.s_a_id,
      pub_id: this.currentPublishId
    }).then(res => {
      if (this.currentPublishId) {
        this.tablePreview(Object.assign({}, row, res.data))
      } else {
        this.tableEdit(Object.assign({}, row, res.data))
        if (mode === 'grain') {
          // @ts-ignore
          this.visibleTitle = row.member_nam +  ' 粮食种粮面积（亩）'
        }
      } 
    })
  }

  public drawerVisible = false
  public currentFieldType = 1
  // 管理耕地信息
  public handlerManageFarmLand(row: IGrain, mode: number) {
    this.currentRow = Object.assign({}, row)
    this.currentFieldType = mode
    this.drawerVisible = true
  }

  // 修改补贴面积
  public handlerChangeEdit(row: IGrain, index: number) {
    this.$set(row, 'bt_size_isEdit', true)
    this.$nextTick(() => {
      this.$refs['bt_size'][index].focus();
    })
  }
  public handerChangeBtSize(row: IGrain) {
    famerServices.updateBtSize({
      family_id: row.family_id,
      bt_size: row.bt_size || 0
    }).then(_ => {
      // @ts-ignore
      row.bt_size_isEdit = false
    })
  }

  // 下载
  public handlerDownload(link: string) {
    const a = document.createElement('a')
    a.href = link
    a.target = '_blank'
    a.click();
  }
}
</script>

<style scoped lang="less">
.action-button {
  margin: 0px 10px 0px 10px;
}
.form-item-class {
  margin-bottom: 0px;
}
.img-box {
  width: 100px;
  height: 100px;
  margin: 10px;
}
.item-blue {
  color: #1989fa;
}

/deep/ .ant-form-item {
  margin-bottom: 4px;
}
/deep/ .ant-modal-body {
  padding: 12px 0 0;
}
/deep/ .ant-modal-footer {
  padding: 12px 20px 36px;
}

.grain-table /deep/ .ant-table {
  th {
    text-align: center;
  }
  .ant-table-tbody > tr:nth-child(1) {
    & td:nth-child(1) {
      text-align: center;
    }
  }
}
</style>
